package com.oracle.controller;

import com.github.pagehelper.Page;
import com.oracle.Service.impl.BookService;
import com.oracle.Service.impl.FeedbackService;
import com.oracle.Service.impl.OrderItemService;
import com.oracle.pojo.Book;
import com.oracle.pojo.Feedback;
import com.oracle.pojo.vo.BookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private FeedbackService feedbackService;


    @RequestMapping("/add")
    public String add(@Validated Book book,Errors errors, MultipartFile image, HttpServletRequest request){

        if (errors!=null&&errors.getFieldErrors()!=null&&errors.getFieldErrors().size()>0){
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors){
                request.setAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
            return "/admin/book";
        }else{
            if (image.getSize()>0){
                try {
                    String newFileName = UUID.randomUUID().toString().replaceAll("-","")+image.getOriginalFilename();
                    image.transferTo(new File(request.getServletContext().getRealPath("/")+"resource/images/"+newFileName));
                    book.setPhoto(newFileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String result = bookService.addBook(book);
            if (result.equals("NO")){
                request.setAttribute("addBookError","请查看上架书本的信息，是否填写错误");
                request.setAttribute("addBookInfo",book);
                return "/admin/book";
            }
            return "redirect:/book/list";
        }


    }

    @RequestMapping("list")
    public String list(@RequestParam(value = "currentPage" ,defaultValue = "1",required = false) Integer currentPage,
                     @RequestParam(value = "pageSize",defaultValue = "3",required = false)  Integer pageSize,
                       BookVo bookVo,Model model){
        //从数据库中取数据
        //使用分页等
        Integer startPage;
        Integer endPage;
        if (currentPage<1){
            currentPage = 1;
        }
        Page<Book> pages = bookService.listBooks_All(currentPage,pageSize,bookVo);
        if (currentPage>pages.getPages()){
            pages = bookService.listBooks_All(pages.getPages(),pageSize,bookVo);
        }
        if (pages.getPages()<10){
            startPage = 1;
            endPage = pages.getPages();
        }else{
            startPage = pages.getPageNum()-4;
            endPage = pages.getPageNum()+5;
        }
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        model.addAttribute("books",pages.getResult());
        model.addAttribute("pageInfo",pages);
        model.addAttribute("bookVo",bookVo);
        //到书本展示页面
        return "/admin/show";
    }

    @RequestMapping("/editor")
    public String editor(Book book,Model model){
        model.addAttribute("update",book);
        return "/admin/updatebook";
    }

    @RequestMapping("/update")
    public String update(Book book,HttpServletRequest request,MultipartFile image){
        if (image.getSize()>0){
            try {
                String newFileName = UUID.randomUUID().toString().replaceAll("-","")+image.getOriginalFilename();
                image.transferTo(new File(request.getServletContext().getRealPath("/")+"resource/images/"+newFileName));
                book.setPhoto(newFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String result = bookService.updateByBid(book);
        if (result.equals("NO")){
            request.setAttribute("update",book);
            request.setAttribute("updateError","修改的信息有错误");
            return "/admin/updatebook";
        }
        return "redirect:/book/list";
    }

    @RequestMapping("/down")
    @ResponseBody
    public Map<String,Object> down(Integer bid){
        int code = 0;
        Map<String,Object> map = new HashMap<String,Object>();
        if (bid!=null&&bid!=0){
            code = bookService.down(bid);
        }
        map.put("code",code);
        return map;
    }

    @RequestMapping("/up")
    @ResponseBody
    public Map<String,Object> up(Integer bid){
        int code = 0;
        Map<String,Object> map = new HashMap<String,Object>();
        if (bid!=null&&bid!=0){
            code = bookService.up(bid);
        }
        map.put("code",code);
        return map;
    }



    //----------------------------------前台---------------------------------------------------
    @RequestMapping("/front/list")
    public String list2(@RequestParam(value = "currentPage" ,defaultValue = "1",required = false) Integer currentPage,
                       @RequestParam(value = "pageSize",defaultValue = "9",required = false)  Integer pageSize,
                       BookVo bookVo,Model model){
        //从数据库中取数据
        //使用分页等
        Integer startPage;
        Integer endPage;
        if (currentPage<1){
            currentPage = 1;
        }
        Page<Book> pages = bookService.listBooks(currentPage,pageSize,bookVo);
        if (currentPage>pages.getPages()){
            pages = bookService.listBooks(pages.getPages(),pageSize,bookVo);
        }
        if (pages.getPages()<10){
            startPage = 1;
            endPage = pages.getPages();
        }else{
            startPage = pages.getPageNum()-4;
            endPage = pages.getPageNum()+5;
        }
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        model.addAttribute("books",pages.getResult());
        model.addAttribute("pageInfo",pages);
        model.addAttribute("bookVo",bookVo);
        //到书本展示页面
        return "/front/show";
    }


    @Transactional
    @RequestMapping("/front/single")
    public String single(Book book,Errors error,Model model){
        if (book.getBid()!=null&&book.getBid()!=0){
            book = bookService.seleteBookbyId(book);
            model.addAttribute("product",book);
            //通过bid查到所有订单
            List<Feedback> list = feedbackService.findFeedbackByBid(book.getBid());
            if (list!=null){
                model.addAttribute("feedbacks",list);
                int size = list.size();
                model.addAttribute("size",size);
            }
        }
        if (book.getCid()!=null&&book.getCid()!=0){
            List<Book> list = bookService.selectBooksByCid(book.getCid());
            model.addAttribute("relatedList",list);
        }

        return "/front/single";
    }
}
